package com.favccxx.search.application;

import com.favccxx.search.domain.conceptmodel.ConceptModel;
import com.favccxx.search.domain.conceptmodel.ConceptModelRepo;
import com.favccxx.search.infrastructure.exception.AppException;
import com.favccxx.search.infrastructure.exception.ExceptionCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ConceptModelService {

    @Autowired
    ConceptModelRepo conceptModelRepo;

    /**
     * Get concept model by id
     *
     * @param id
     * @return
     */
    public ConceptModel findById(String id) {
        Optional<ConceptModel> opt = conceptModelRepo.findById(id);
        if (opt.isPresent()) {
            return opt.get();
        }
        return null;
    }

    /**
     * Find concept model by project id and concept model code
     *
     * @param projectId
     * @param code
     * @return
     */
    public ConceptModel findByProjectIdAndCode(String projectId, String code) {
        return conceptModelRepo.findByProjectIdAndCode(projectId, code);
    }

    public ConceptModel saveConceptModel(ConceptModel conceptModel) {
        return conceptModelRepo.insert(conceptModel);
    }

    public ConceptModel updateConceptModel(ConceptModel conceptModel) {
        Optional<ConceptModel> opt = conceptModelRepo.findById(conceptModel.getId());
        if (opt == null) {
            throw new AppException(ExceptionCode.ConceptModel.CONCEPT_MODEL_NOT_EXIST);
        }

        ConceptModel existModel = opt.get();
        if (StringUtils.isNotBlank(conceptModel.getCode())) {
            existModel.setCode(conceptModel.getCode());
        }
        if (StringUtils.isNotBlank(conceptModel.getName())) {
            existModel.setName(conceptModel.getName());
        }
        if (StringUtils.isNotBlank(conceptModel.getType())) {
            existModel.setType(conceptModel.getType());
        }
        if (StringUtils.isNotBlank(conceptModel.getProjectId())) {
            existModel.setType(conceptModel.getProjectId());
        }
        if (StringUtils.isNotBlank(conceptModel.getDescription())) {
            existModel.setDescription(conceptModel.getDescription());
        }
        if (conceptModel.getModelFields() != null) {
            existModel.setModelFields(conceptModel.getModelFields());
        }
        conceptModelRepo.save(existModel);
        return existModel;
    }

    public void deleteById(String id) {
        conceptModelRepo.deleteById(id);
    }


    public List<ConceptModel> findAll() {
        return conceptModelRepo.findAll();
    }


}
